package com.ww.springboot.boot.java8.completablefuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-01-20 15:21
 */
public class CompletableFutureDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //有返回值
        CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("运行任务");
            return 1;
        });
        System.out.println("result:" + completableFuture.get());

        //无返回值
        CompletableFuture completableFuture2 = CompletableFuture.runAsync(() -> System.out.println("运行任务"));
        System.out.println("result:" + completableFuture2.get());

        //批量
        List<Integer> list = IntStream.range(0,10).boxed().collect(Collectors.toList());
        List<Integer> result = new ArrayList<>();

       CompletableFuture[] completableFutureList = list.stream().map(i->CompletableFuture.supplyAsync(() -> {
            System.out.println("运行任务");
           try {
               TimeUnit.SECONDS.sleep(i);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           return i;
           //whenCompleteAsync可以将上一个任务的结果传递下去
        })).toArray(CompletableFuture[]::new);
        System.out.println(result);
        //阻塞
        CompletableFuture.allOf(completableFutureList).join();
        //批量获取
        System.out.println(result);
    }
}
